package Pet.Management.repository;

import Pet.Management.domain.entity.PetCareOrder;
import org.springframework.stereotype.Repository;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.ResultSet;
import java.util.List;
import java.util.Optional;

@Repository
public class PetCareOrderRepository {
    
    private static final Logger logger = LoggerFactory.getLogger(PetCareOrderRepository.class);
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private final RowMapper<PetCareOrder> orderRowMapper = (ResultSet rs, int rowNum) -> {
        try {
            PetCareOrder order = new PetCareOrder();
            order.setId(rs.getLong("id"));
            order.setPublisherId(rs.getLong("publisher_id"));
            order.setAcceptorId(rs.getLong("acceptor_id"));
            order.setPetName(rs.getString("pet_name"));
            order.setPetType(rs.getString("pet_type"));
            order.setServiceType(rs.getString("service_type"));
            order.setStartTime(rs.getTimestamp("start_time") != null ? 
                rs.getTimestamp("start_time").toLocalDateTime() : null);
            order.setEndTime(rs.getTimestamp("end_time") != null ? 
                rs.getTimestamp("end_time").toLocalDateTime() : null);
            order.setPrice(rs.getBigDecimal("price"));
            order.setDescription(rs.getString("description"));
            order.setStatus(rs.getInt("status"));
            order.setAcceptTime(rs.getTimestamp("accept_time") != null ? 
                rs.getTimestamp("accept_time").toLocalDateTime() : null);
            order.setCreateTime(rs.getTimestamp("create_time") != null ? 
                rs.getTimestamp("create_time").toLocalDateTime() : null);
            order.setUpdateTime(rs.getTimestamp("update_time") != null ? 
                rs.getTimestamp("update_time").toLocalDateTime() : null);
            return order;
        } catch (Exception e) {
            logger.error("解析订单数据失败", e);
            throw e;
        }
    };

    public PetCareOrder save(PetCareOrder order) {
        if (order.getId() == null) {
            String sql = "INSERT INTO pet_care_orders (publisher_id, acceptor_id, pet_name, pet_type, service_type, " +
                    "start_time, end_time, price, description, status, accept_time, create_time, update_time) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            jdbcTemplate.update(sql,
                order.getPublisherId(),
                order.getAcceptorId(),
                order.getPetName(),
                order.getPetType(),
                order.getServiceType(),
                order.getStartTime(),
                order.getEndTime(),
                order.getPrice(),
                order.getDescription(),
                order.getStatus(),
                order.getAcceptTime(),
                order.getCreateTime(),
                order.getUpdateTime()
            );
        } else {
            String sql = "UPDATE pet_care_orders SET publisher_id=?, acceptor_id=?, pet_name=?, pet_type=?, " +
                    "service_type=?, start_time=?, end_time=?, price=?, description=?, status=?, " +
                    "accept_time=?, create_time=?, update_time=? WHERE id=?";
            
            jdbcTemplate.update(sql,
                order.getPublisherId(),
                order.getAcceptorId(),
                order.getPetName(),
                order.getPetType(),
                order.getServiceType(),
                order.getStartTime(),
                order.getEndTime(),
                order.getPrice(),
                order.getDescription(),
                order.getStatus(),
                order.getAcceptTime(),
                order.getCreateTime(),
                order.getUpdateTime(),
                order.getId()
            );
        }
        return order;
    }

    public Optional<PetCareOrder> findById(Long id) {
        String sql = "SELECT * FROM pet_care_orders WHERE id = ?";
        try {
            List<PetCareOrder> results = jdbcTemplate.query(sql, orderRowMapper, id);
            return results.isEmpty() ? Optional.empty() : Optional.of(results.get(0));
        } catch (Exception e) {
            return Optional.empty();
        }
    }

    public List<PetCareOrder> findAvailableOrders() {
        String sql = "SELECT * FROM pet_care_orders WHERE status = 0 AND acceptor_id IS NULL";
        return jdbcTemplate.query(sql, orderRowMapper);
    }

    public List<PetCareOrder> findByPublisherId(Long publisherId) {
        String sql = "SELECT * FROM pet_care_orders WHERE publisher_id = ? ORDER BY create_time DESC";
        logger.info("执行查询发布订单SQL: {}, publisherId: {}", sql, publisherId);
        try {
            List<PetCareOrder> orders = jdbcTemplate.query(sql, orderRowMapper, publisherId);
            logger.info("查询到{}条发布订单", orders.size());
            return orders;
        } catch (Exception e) {
            logger.error("查询发布订单失败", e);
            throw e;
        }
    }

    public List<PetCareOrder> findByAcceptorId(Long acceptorId) {
        String sql = "SELECT * FROM pet_care_orders WHERE acceptor_id = ? ORDER BY accept_time DESC";
        logger.info("执行查询接受订单SQL: {}, acceptorId: {}", sql, acceptorId);
        try {
            List<PetCareOrder> orders = jdbcTemplate.query(sql, orderRowMapper, acceptorId);
            logger.info("查询到{}条接受订单", orders.size());
            return orders;
        } catch (Exception e) {
            logger.error("查询接受订单失败", e);
            throw e;
        }
    }
} 